//
// Created by bjliuyong on 2021/6/11.
//

#include "../../include/gc/mark_clean.h"


MarkClean::MarkClean(MemoryChunk *memoryChunk) : m_mem_chunk(memoryChunk) {}

MarkClean::~MarkClean() {
    INFO_PRINT("[调用析构函数%s]释放资源\n", __func__);
}

void MarkClean::run() {
    PRINT("[标记-清除算法]开始运行\n");
    mark();
    clean();
}


void MarkClean::mark() {
    PRINT("\t 开始执行标记操作\n");
    list<MemoryCell *> *mem_cells = m_mem_chunk->get_used_table();
    list<MemoryCell *>::iterator iterator;
    for (iterator = mem_cells->begin(); iterator != mem_cells->end(); iterator++) {
        MemoryCell *cell = *iterator;
        if (cell->get_size() == 4) {
            cell->set_mark(true);
        }
    }
}

void MarkClean::clean() {
    PRINT("\t 开始执行清理操作\n");
    list<MemoryCell *> *mem_cells = m_mem_chunk->get_used_table();
    list<MemoryCell *>::iterator iterator;

    bool f = false;
    for (iterator = mem_cells->begin(); iterator != mem_cells->end();) {
        MemoryCell *cell = *iterator;
        if (!cell->get_mark()) {
            //clean
            iterator = m_mem_chunk->get_used_table()->erase(iterator);
            m_mem_chunk->get_available_table()->push_front(new MemoryCell(cell->get_start(), cell->get_size()));
            m_mem_chunk->desc_used_cell_num(cell->get_size());
            delete cell;
            f = true;
        } else {
            iterator++;
        }
    }
    if (!f) {
        ERROR_PRINT("[GC后]没有可回收的内存，无法分配内存，执行Full GC\n");
        exit(1);
    }
}
